#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from fastapi import FastAPI
from starlette.staticfiles import StaticFiles

from app import errors, middleware
from app.controller import RegisterRouterList

# 根据配置进行初始化
from app.dao.models.mysql_gen import metadata
from app.config import globalAppSettings
from app.dao.base_dao import engine

# from app.middleware import CORSMiddleware
from fastapi.middleware.cors import CORSMiddleware


def Init(server: FastAPI):
    """初始化项目"""
    # 挂载静态资源目录
    server.mount("/api/static", StaticFiles(directory="static"), name="static")

    # if globalAppSettings.new_tables:
    # 根据model创建数据库表
    metadata.create_all(engine)

    # 注册自定义错误处理器
    errors.registerCustomErrorHandle(server)
    # 注册中间件
    middleware.registerMiddlewareHandle(server)

    # 允许跨域的源列表，可以根据需要做精确配置
    origins = [
        "http://localhost:8888",
        "http://127.0.0.1:3000",
        "http://172.17.62.81:9990",
        "http://127.0.0.1:9990",
        "http://localhost:9990",
    ]

    server.add_middleware(
        CORSMiddleware,
        allow_origins=[
            "*"
        ],  # 指定允许跨域的域名列表 和 allow_credentials=True 不能同时生效
        allow_credentials=False,  # 是否允许携带 Cookie
        allow_methods=["*"],  # 允许的请求方法，如 GET, POST 等
        allow_headers=["*"],  # 允许的请求头，如 Authorization, Content-Type 等
    )

    # 加载路由
    for item in RegisterRouterList:
        server.include_router(item.router)
